#include <iostream>
#include <pthread.h>
#include <cstdlib>
#include <unistd.h>

using namespace std;

#define NUM 5

void* Routine(void* args)
{
  int cnt = rand() % 5 + 5;
  while(cnt)
  {
    cout << "thread: " << pthread_self() << "| count: " << cnt << " is running" << endl;
    cnt--;
    sleep(1);
  }
  return nullptr;
}

int main()
{
  srand((unsigned long)time(nullptr));
  //创建线程
  pthread_t tids[NUM];
  for(int i = 0; i < NUM; i++)
  {
    pthread_create(&tids[i], nullptr, Routine, nullptr);    
  }
  //主线程等待新线程
  cout << "main thread join begin..." << endl;
  for(int i = 0; i < NUM; i++)
  {
    if(pthread_join(tids[i], nullptr) == 0)
    {
        cout << "tid: " << tids[i] << " exit" << endl;
    }
  }
  cout << "main thread join end..." << endl;
  return 0;
}
